class code3 {
    int[] tmp1,tmp2;
    int[] ret;
    public List<Integer> countSmaller(int[] nums) {
        ret = new int[nums.length];
        int[] index = new int[nums.length];
        for(int i=0;i<nums.length;i++) {
            index[i] = i;
        }
        tmp1 = new int[nums.length];
        tmp2 = new int[nums.length];
        mergeSort(nums,index,0,nums.length-1);
        List<Integer> rets = new ArrayList<>();
        for(int re:ret) {
            rets.add(re);
        }
        return rets;
    }
    public void mergeSort(int[] nums,int[] index,int left,int right) {
        //1.出口
        if(left>=right) return ;
        //2.中间值
        int mid = (left+right)/2;
        //3.算都在左边和都在右边的+排序
        mergeSort(nums,index,left,mid);
        mergeSort(nums,index,mid+1,right);
        //4.合并数组
        int cur1=left,cur2=mid+1,i=0;
        while(cur1<=mid&&cur2<=right) {
            if(nums[cur1]<=nums[cur2]) {
                tmp1[i] = nums[cur2];
                tmp2[i++] = index[cur2++];
            } else {
                ret[index[cur1]] += right-cur2+1;
                tmp1[i] = nums[cur1];
                tmp2[i++] = index[cur1++];
            }
        }
        //处理剩下的元素
        while(cur1<=mid) {
            tmp1[i] = nums[cur1];
            tmp2[i++] = index[cur1++];
        }
        while(cur2<=right) {
            tmp1[i] = nums[cur2];
            tmp2[i++] = index[cur2++];
        }
        //5.映射
        for(int j=left;j<=right;j++) {
            nums[j] = tmp1[j-left];
            index[j] = tmp2[j-left];
        }
    }
}